package com.jzg.mvc.api.user;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.jzg.common.controller.BaseController;
import com.jzg.common.model.biz.Cab;
import com.jzg.common.model.biz.CabStoreLog;
import com.jzg.common.model.biz.CabStoreUser;
import com.jzg.common.model.biz.CabUser;
import com.jzg.common.model.sys.SysUser;
import com.jzg.common.util.UuidUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Path(value = "/api/cab/user", viewPath = "")
public class UserControler extends BaseController{
	
	public void getUsers() {
		String cabinetId=this.getPara("cabinetId");
		String sqlExceptSelect = " FROM "+SysUser.TABLE_NAME+" WHERE 1=1 ";
		if(StrKit.isBlank(cabinetId)) {
			this.renderError("柜子ID必填！");
			return;
		}
		if(StrKit.isBlank(cabinetId)) {
			sqlExceptSelect += " AND ORGID IN (SELECT orgId FROM "+Cab.TABLE_NAME+" WHERE license='"+cabinetId+"' ) ";
		}
		List<SysUser> users=SysUser.dao.find("SELECT * "+sqlExceptSelect,cabinetId);
		this.renderSuccess("成功！", JsonKit.toJson(users));
	}
	
	/**
	 * 柜子用户列表
	 */
	public void getCabUsers() {
		String userId = getPara("userId");
		String cabId = getPara("cabId");
		String caseNo = getPara("caseNo");
		String key = getPara("key");
		
		String sqlExceptSelect = " FROM "+CabUser.TABLE_NAME+" O,"+SysUser.TABLE_NAME+" U WHERE 1=1 AND O.USERID=U.ID ";
		if(StrKit.isBlank(cabId)) {
			this.renderError("柜子ID必填！");
			return;
		}
		
		if(!StrKit.isBlank(userId)) {
			sqlExceptSelect += " AND O.ID <> '"+userId+"' ";
		}
		if(!StrKit.isBlank(cabId)) {
			sqlExceptSelect += " AND CABID='"+cabId+"'  ";
		}
		if(!StrKit.isBlank(key)) {
			sqlExceptSelect += " AND (O.roleKey like  '%"+key+"%' or O.roleName like  '%"+key+"%' or U.NAME LIKE  '%"+key+"%' )";
		}
		
		List<CabUser> users=CabUser.dao.find("SELECT O.userId as id,O.roleName,U.orgId,U.username,U.name,U.PHOTOIMG, "
				+ " (CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM BIZ_CAB_STORE_USER WHERE STOREID='"+caseNo+"' AND USERID=O.USERID)>0 THEN TRUE ELSE  FALSE END ) AS isAuth "+sqlExceptSelect);
		this.renderSuccess("成功！", users);
	}
	
	/**
	 * 案件授权
	 */
	@Before(POST.class)
	public void saveAuth() {
		@SuppressWarnings("unused")
		List<UploadFile> files = this.getFiles("files");
		String userId = getPara("userId");
		String caseNo = getPara("caseNo");
		String cabId = getPara("cabId");
		String users = getPara("users");
		
		if(StrKit.isBlank(userId)) {
			renderError("参数必填！");
			return;
		}
		
		if(StrKit.isBlank(cabId)) {
			renderError("参数必填！");
			return;
		}
		
		if(StrKit.isBlank(users)) {
			renderError("授权用户不能为空！");
			return;
		}
		
		SysUser user = SysUser.dao.findFirst("SELECT * FROM "+SysUser.TABLE_NAME+" where ID=? ",userId);
		if(user==null) {
			renderError("非法操作用户！");
			return;
		}
		
		try {
			JSONArray userArr = JSONArray.fromObject(users);
			if(userArr!=null && userArr.size()>0) {
				//Db.delete("delete from "+CabStoreUser.TABLE_NAME+" where storeId=? and userId!=? ",caseNo,userId);
				for (Object obj : userArr) {
					JSONObject authObj = (JSONObject)obj;
					String id = authObj.getString("id");
					if(StrKit.equals("add", authObj.getString("type"))) {
						SysUser u = SysUser.dao.findById(id);
						if(u!=null) {
							CabStoreUser cabStoreUser = CabStoreUser.dao.findFirst("select * from "+CabStoreUser.TABLE_NAME+" where cabId=? and storeId=? and userId=? ",cabId,caseNo,id);
							if(cabStoreUser==null) {
								cabStoreUser = new CabStoreUser();
								cabStoreUser.setId(UuidUtil.getUUID());
								cabStoreUser.setCabId(cabId);
								cabStoreUser.setStoreId(caseNo);
								cabStoreUser.setUserId(id);
								cabStoreUser.setType("0");
								if(cabStoreUser.save()) {
									CabStoreLog cabStoreLog = new CabStoreLog();
									cabStoreLog.setId(UuidUtil.getUUID());
									cabStoreLog.setCabId(cabId);
									cabStoreLog.setStoreId(caseNo);
									cabStoreLog.setAuthUserId(id);
									cabStoreLog.setCreateUserId(userId);
									cabStoreLog.setStatus("0");
									//cabStoreLog.setCreateUserName(u.getNAME());
									cabStoreLog.setCreateTime(new Date(System.currentTimeMillis()));
									cabStoreLog.setType("1");
									cabStoreLog.save();						
								}
							}
						}
					}else if(StrKit.equals("cancel", authObj.getString("type"))) {
						Db.delete("delete from "+CabStoreUser.TABLE_NAME+" where cabId=? and storeId=? and userId=? ",cabId,caseNo,id);
						CabStoreLog cabStoreLog = new CabStoreLog();
						cabStoreLog.setId(UuidUtil.getUUID());
						cabStoreLog.setCabId(cabId);
						cabStoreLog.setStoreId(caseNo);
						cabStoreLog.setAuthUserId(id);
						cabStoreLog.setCreateUserId(userId);
						cabStoreLog.setStatus("1");
						//cabStoreLog.setCreateUserName(user.getNAME());
						cabStoreLog.setCreateTime(new Date(System.currentTimeMillis()));
						cabStoreLog.setType("1");
						cabStoreLog.save();		
						
					}else {
					}
				}
			}
			renderSuccess("授权成功！");
		} catch (Exception e) {
			renderError("授权失败！异常【"+e.getMessage()+"】");
			e.printStackTrace();
			return;
		}
		
	}
	
	/**
	 * 获取柜子可授权人员
	 */
	public void getCabAuthUsers() {
		String cabId = getPara("cabId");
		String keywords = get("keywords");
		Cab cab = Cab.dao.findById(cabId);
		if(cab==null) {
			renderError("未找到柜子信息，请刷新重试！");
			return;
		}
		StringBuffer sb = new StringBuffer();
		List<Record> records=Db.use("plga").find("select * from Manage where NGroup != 4 ");
		if(records!=null && records.size()>0) {
			for (Record record : records) {
				sb.append("'").append(record.getStr("NId")).append("'").append(",");
			}
		}
		String sqlExceptSelect = " FROM "+SysUser.TABLE_NAME+" U WHERE  SRC='1' ";
		if(!StrKit.isBlank(keywords)) {
			sqlExceptSelect += " AND (NAME LIKE '%"+keywords+"%' ) ";
		}
		if(!StrKit.isBlank(sb.toString())) {
			sqlExceptSelect += " AND U.ID IN ("+sb.substring(0, sb.length() - 1)+") ";
		}
		List<SysUser> users = SysUser.dao.find("SELECT U.ID AS id,U.NAME AS name,U.PHOTOIMG "+sqlExceptSelect);
		for (SysUser sysUser : users) {
			CabUser cabUser = CabUser.dao.findFirst("select * from "+CabUser.TABLE_NAME+" where cabId='"+cabId+"' and userId='"+sysUser.getStr("id")+"' ");
			if(cabUser!=null) {
				if(cabUser.getRoleKey().contains("all")) {
					sysUser.setIsAuth("0");
				}else {
					sysUser.setIsAuth("1");
				}
			}else {
				sysUser.setIsAuth("");
			}
		}
		renderSuccess("查询成功！", users);
	}
	
	/**
	 * 柜子授权
	 */
	@Before(POST.class)
	public void saveCabAuth() {
		@SuppressWarnings("unused")
		List<UploadFile> files = this.getFiles("files");
		String userId = getPara("userId");
		String cabId = getPara("cabId");
		String users = getPara("users");
		
		if(StrKit.isBlank(userId)) {
			renderError("参数必填！");
			return;
		}
		
		if(StrKit.isBlank(cabId)) {
			renderError("参数必填！");
			return;
		}
		
		if(StrKit.isBlank(users)) {
			renderError("授权用户不能为空！");
			return;
		}
		
		SysUser user = SysUser.dao.findById(userId);
		if(user==null) {
			renderError("非法操作用户！");
			return;
		}
		
		try {
			JSONArray userArr = JSONArray.fromObject(users);
			if(userArr!=null && userArr.size()>0) {
				for (Object obj : userArr) {
					JSONObject authObj = (JSONObject)obj;
					String id = authObj.getString("id");
					CabUser cabUser = CabUser.dao.findFirst("select * from "+CabUser.TABLE_NAME+" where userId=? and cabId=? ",id,cabId);
					if(StrKit.equals("add", authObj.getString("type"))) {
						String auth = authObj.getString("auth");
						SysUser sysUser = SysUser.dao.findById(id);
						if(cabUser == null) {
							cabUser = new CabUser();
							cabUser.setId(UuidUtil.getUUID());
							cabUser.save();
						}
						cabUser.setCabId(cabId);
						cabUser.setUserId(sysUser.getID());
						if(StrKit.equals("0", auth)) {
							cabUser.setRoleName("超级管理员");
							cabUser.setRoleKey("setting|all");
						}else if(StrKit.equals("1", auth)) {
							cabUser.setRoleName("法制专员|");
							cabUser.setRoleKey("setting|");
						}else {
						}
						cabUser.update();
					}else if(StrKit.equals("cancel", authObj.getString("type"))) {
						if(cabUser!=null) {
							cabUser.delete();
						}
					}else {
					}
				}
			}
			renderSuccess("授权成功！");
		} catch (Exception e) {
			renderError("授权失败！异常【"+e.getMessage()+"】");
			e.printStackTrace();
			return;
		}
		
	}
	
	public void synUser() {
		List<Record> records=Db.use("plga").find("select * from Manage ");
		int i=0;
		for (Record record : records) {
			String NGroup=record.getStr("SMayGroups");
    		if(!StrKit.isBlank(NGroup)) {
    			String[] NGroups=NGroup.split("\\|");
    			for(String group:NGroups) {
    				if(!StrKit.isBlank(group)) {
    					Cab cab = Cab.dao.findFirst("select * from "+Cab.TABLE_NAME+" where orgId=? ",group);
        				if(cab!=null) {
        					CabUser cabUser = CabUser.dao.findFirst("select * from "+CabUser.TABLE_NAME+" where cabId=? and userId=? ",cab.getId(),record.getStr("NId"));
        					if(cabUser==null) {
        						cabUser = new CabUser();
        						cabUser.setId(UuidUtil.getUUID());
        						cabUser.setCabId(cab.getId());
        						cabUser.setUserId(record.getStr("NId"));
        						if(StrKit.equals("21", record.getStr("NGroup"))) {
        							cabUser.setRoleName("法制专员|");
        							cabUser.setRoleKey("setting");
        						}else {
        							cabUser.setRoleName("超级管理员");
        							cabUser.setRoleKey("setting|all");
        						}
        						cabUser.save();
        						i++;
        					}
        				}
    				}
    			}
    		}
		}
		renderSuccess("操作成功！【"+i+"】");
	}
	
	ExecutorService executor = Executors.newFixedThreadPool(20);
	public void synUserAll() {
		renderSuccess("操作成功，已启动异步同步进程！");
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
	        @Override
	        public Integer get() {
	            try {
	            	List<Record> records=Db.use("plga").find("select * from Manage where NGroup != 4 ");
	            	List<Cab> cabs = Cab.dao.findAll();
	            	if(records!=null && records.size()>0 && cabs!=null && cabs.size()>0) {
	            		for (Cab cab : cabs) {
		            		for (Record record : records) {
		            			CabUser cabUser = CabUser.dao.findFirst("select * from "+CabUser.TABLE_NAME+" where cabId=? and userId=? ",cab.getId(),record.getStr("NId"));
		            			if(cabUser==null) {
	        						cabUser = new CabUser();
	        						cabUser.setId(UuidUtil.getUUID());
	        						cabUser.setCabId(cab.getId());
	        						cabUser.setUserId(record.getStr("NId"));
	        						if(StrKit.equals("21", record.getStr("NGroup"))) {
	        							cabUser.setRoleName("法制专员|");
	        							cabUser.setRoleKey("setting");
	        						}else {
	        							cabUser.setRoleName("超级管理员");
	        							cabUser.setRoleKey("setting|all");
	        						}
	        						cabUser.save();
	        					}
							}
						}
	            	}
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	            return 3;
	        }
	    }, executor);
	    future.thenAccept(e -> System.out.println(e));
	}
	
}
